<template>
  <el-dialog :visible.sync="visible"
             :close-on-click-modal="false"
             append-to-body
             :close-on-press-escape="false"
             @closed="clearFormData"
             width="1100px"
             custom-class="div-background">
    <div slot="title">
      <span>{{!dataForm.gadgetId ? $t('update'): $t('custom.widget.addnewwidget')}}</span>
      <view-linked-info :linkKey="'Widget'"></view-linked-info>
    </div>
    <el-form :model="dataForm"
             :rules="dataRule"
             :inline="false"
             ref="dataForm"
             @keyup.enter.native="dataFormSubmitHandle()"
             label-width="180px"
             v-loading="loading"
             label-position="right">
      <div>
        <!-- <div class="search-div" style="">
            <el-input  placeholder="Search"></el-input>
        </div> -->
        <el-container>
          <el-aside width="710px">
            <el-tabs value="Published">
              <el-tab-pane label="Published"
                           name="Published">
                <div style="height:220px;display:flex;flex-wrap: wrap;align-content:space-between;margin-top:5px;padding:0 5px">
                  <div class="cursor_pointer widget_card"
                       v-for="(layoutItem,index) in layoutListsOfwidget"
                       :key="layoutItem.key"
                       style="width: 100px;height: 100px;padding:10px;"
                       :style="(index+1)%6===0?'margin-right:0':'margin-right:20px'">
                    <div @click="selectGadget(layoutItem.key)">
                      <img :src="layoutItem.imageUrl"
                           style="width: 40px;height: 40px;display: block;"
                           fit="fill">
                      <div class="bottom clearfix"
                           style="width:80px;margin-top:6px">
                        <span style="font-weight:500;font-size:12px;color:#404040;line-height:17px;word-break:break-all;overflow: hidden;">{{layoutItem.title.split(' ')[0]}}</span><br>
                        <span style="font-weight:500;font-size:12px;color:#404040;line-height:17px;word-break:break-all;overflow: hidden;">{{layoutItem.title.split(' ')[1]}}</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div style="margin-top:20px">
                  <el-pagination style="text-align: center;"
                                 layout="prev, pager, next"
                                 :current-page.sync="currentPage"
                                 :page-size="12"
                                 :total="totalRecord">
                  </el-pagination>
                </div>
              </el-tab-pane>
              <el-tab-pane label="Published"
                           name="Publisheds"
                           v-if="pageId&&businessTypeListrecord.length>0">
                <div class="widget_data_list"
                     v-loading="widgetLoading">
                  <el-checkbox-group v-model="checkedCities"
                                     @change="handleCheckedCitiesChange">
                    <el-checkbox v-for="(val,index) in  businessTypeListrecord.slice((addCurrentPage-1)*5,addCurrentPage*5)"
                                 :label="val.name"
                                 :key="index"
                                 :class="'checked'?'el-checkted':''">
                      <div class="item_widget3">
                        <div class="item_widget_content">
                          <div>{{val.name}}</div>
                          <div>{{val.description}}</div>
                        </div>
                        <div class="item_widget_ri"
                             @click.prevent="PreviewWidget(val)">
                          <el-tooltip class="item"
                                      :open-delay="1000"
                                      effect="dark"
                                      content="Preview"
                                      placement="bottom-start">
                            <el-button></el-button>
                          </el-tooltip>
                        </div>
                      </div>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <div>
                  <el-pagination layout="prev, pager, next"
                                 :total="businessTypeListrecord.length"
                                 :page-size="5"
                                 :page-count='addCurrentPage'
                                 :current-page='addCurrentPage'
                                 @current-change="handleCurrentChange">
                  </el-pagination>
                </div>
                <template slot="footer">
                  <el-button size="small"
                             @click="dialog = false">{{ $t('Cancel') }}</el-button>
                  <el-button type="primary"
                             size="small"
                             @click="addGadgetToPageGroup()">{{ $t('Add') }}</el-button>
                </template>
              </el-tab-pane>
            </el-tabs>
          </el-aside>
          <el-main>
            <div class="right-text">
              <h2>Create your widget</h2><br>
              <span>Create your own custom widget using our new, intuitive widgets.</span><br>
              <h3>Select widget type to start creating your widget or view tutorial to learn more.</h3><br>
              <!-- <el-button size="small" type="primary">View Tutorial</el-button> -->
            </div>

          </el-main>
        </el-container>
      </div>

    </el-form>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           ref="model"
           @refreshDataList="getDataList"
           :defaultDataset="defaultDataset"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :showMoreEditSetting="queryModelDefaultSetting.showMoreEditSetting"
           :updateGadget="upgradeGadgetSetting"
           :mappingForm="mappingFormSetting" />
  </el-dialog>
</template>

<script>
import { getUUID } from '@/utils'
import { dashboardGadgetList, defaultGadgetSettingList } from '@/utils/data-json'
import mixinDashboardViewModule from '@/mixins/dashboard-view-module'

export default {
  components: { model: () => import('@/components/gadget/query-model/query-model') },
  data () {
    return {
      widgetLoading: false,
      checkedGauge: [],
      businessTypeListrecord: [],
      checkedCities: [],
      visible: false,
      loading: false,
      currentPage: 1,
      addCurrentPage: 1,
      integrationList: [],
      dataForm: {
        id: null,
        name: null,
        /// integration: [],
        businessId: null,
        gadgetId: null,
        businessType: null,
        gadgetType: null,
        gadgetSetting: {},
        datasetSetting: {},
        formSetting: {},
        filterSettings: {},
        sqlExpress: {},
        type: 1,
        description: null,
        reuse: true,
        tenantCode: this.$store.state.user.tenantCode,
        status: null,
        owner: null,
        // about DA
        internalNotes: null,
        uat: null,
        overheadFilters: null,
        allClientsQa: null,
        reportingQa: null,
        priority: null,
        eta: null,
        client: null,
        progress: null
      },
      userList: [],
      activeName: 'first',
      oldGadgetType: null,
      queryModelDefaultSetting: {
        showSetting: false,
        showMoreEditSetting: false,
        dataInfo: {
        }
      },
      mappingFormSetting (to, from) {

      }
    }
  },
  props: {
    isSlicer: {
      type: Boolean
    },
    defaultDataset: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    visible (val) {
      if (!val) {

      }
    }
  },
  mixins: [mixinDashboardViewModule],
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  computed: {
    GadgetList: {
      get () {
        let tempList = []
        tempList = this.userGadgetList
        return tempList
      },
      set (newVal) {
        this.businessTypeListrecord = newVal
      }
    },
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        // integration: [
        //   { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        // ],
        businessType: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        status: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    },
    layoutListsOfwidget () {
      var tempList = []
      if (this.IsSlicer() || this.isSlicer) {
        tempList = this._.reject(this._.reject(this._.reject(this._.reject(this._.reject(dashboardGadgetList, { key: '' }), { group: '' }), { group: 'customized' }), { group: 'inDev' }), { type: 'widget' })
      } else {
        tempList = this._.reject(this._.reject(this._.reject(this._.reject(this._.reject(dashboardGadgetList, { key: '' }), { group: '' }), { group: 'customized' }), { group: 'inDev' }), { type: 'slicer' })
      }
      if (!this.$hasPermission('sys:widget:status:in-dev')) {
        tempList = this._.reject(tempList, { status: 'In-Dev' })
      }
      if (!this.$hasPermission('sys:widget:status:published')) {
        tempList = this._.reject(tempList, { status: 'Published' })
      }
      tempList = this._.chunk(tempList, 12)
      return tempList[this.currentPage - 1]
    },
    totalRecord () {
      var tempList = []
      if (this.IsSlicer()) {
        tempList = this._.reject(this._.reject(this._.reject(this._.reject(this._.reject(dashboardGadgetList, { key: '' }), { group: '' }), { group: 'customized' }), { group: 'inDev' }), { type: 'widget' })
      } else {
        tempList = this._.reject(this._.reject(this._.reject(this._.reject(this._.reject(dashboardGadgetList, { key: '' }), { group: '' }), { group: 'customized' }), { group: 'inDev' }), { type: 'slicer' })
      }
      if (!this.$hasPermission('sys:widget:status:in-dev')) {
        tempList = this._.reject(tempList, { status: 'In-Dev' })
      }
      if (!this.$hasPermission('sys:widget:status:published')) {
        tempList = this._.reject(tempList, { status: 'Published' })
      }
      return tempList.length
    }
  },
  created () {
    this.getUserList()
    this.getIntegrationList()
  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        if (this.dataForm.gadgetId) {
          this.getInfo()
        } else {
          this.dataForm.gadgetId = getUUID()
        }
      })
    },
    IsSlicer () {
      let path = window.location.pathname
      if (path === '/Slicer' || path === '/CrossTenantSlicer') {
        return true
      } else {
        return false
      }
    },
    getInfo () {
      var _self = this
      _self.loading = true
      const params = {
        gadgetId: _self.dataForm.gadgetId
      }
      this.$interface.reports.getReportSettingInfo(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return _self.$message.error(res.msg)
        }
        _self.dataForm = res.data
        if (_self.dataForm.gadgetType) {
          _self.oldGadgetType = _self.dataForm.gadgetType
        }
        _self.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    selectGadget (key) {
      const widget = {
        businessId: '',
        gadgetId: getUUID(),
        gadgetType: key,
        gadgetSetting: this.getGadgetSetting(key),
        reuse: true,
        datasetSetting: {}
      }
      this.showWidgetDesign(widget)
      key = ''
    },
    upgradeGadgetSetting () {

    },
    handleCheckedCitiesChange (value) {
      this.checkedGauge = value
    },
    checkedName (val) {
      this.currentPage = 1
      if (this.businessTypeForWidget === 'Template') {
        this.GadgetList = this.filterHasWidget(this.userGadgetList).filter(e => e.businessType === 'Template').filter(e => e.name.toLowerCase().indexOf(val.toLowerCase()) !== -1)
      } else {
        this.GadgetList = this.filterHasWidget(this.userGadgetList).filter(e => e.name.toLowerCase().indexOf(val.toLowerCase()) !== -1)
      }
    },
    getGadgetSetting (key) {
      return defaultGadgetSettingList.find(e => e.gadgetType === key).gadgetSetting || {}
    },
    filterHasWidget (value) {
      let tempList = value
      if (this.businessTypeForWidget !== 'MSPbots Internal') {
        if (this.businessTypeForWidget === 'Template') {
          tempList = this._.reject(tempList, { businessType: 'Custom' })
        }
        tempList = this._.reject(tempList, { businessType: 'MSPbots Internal' })
      }
      let arr = []
      let tempListArr = []
      this.gadgets.forEach(element => {
        arr.push(element.i)
      })
      tempList.forEach(element => {
        if (arr.indexOf(element.gadgetId) === -1) {
          tempListArr.push(element)
        }
      })
      return tempListArr
    },
    handleCurrentChange: function (currentPage) {
      this.addCurrentPage = currentPage
    },
    PreviewWidget (item) {
      this.commandClick(item)
    },
    // commandClick (row) {
    //   this.queryModelDefaultSetting.dataInfo.businessId = row.businessId
    //   this.queryModelDefaultSetting.dataInfo.gadgetId = row.gadgetId
    //   this.queryModelDefaultSetting.dataInfo.gadgetType = row.gadgetType
    //   this.queryModelDefaultSetting.dataInfo.gadgetSetting = row.gadgetSetting
    //   this.$nextTick(() => {
    //     this.$store.state.isWidget = true
    //     this.showQueryModel()
    //   })
    // },
    showWidgetDesign (row) {
      this.queryModelDefaultSetting.dataInfo.datasetSetting = {}
      this.queryModelDefaultSetting.dataInfo = Object.assign(this._.merge(this.queryModelDefaultSetting.dataInfo, row))
      this.queryModelDefaultSetting.showMoreEditSetting = true
      this.$nextTick(() => {
        this.$store.state.isWidget = true
        this.showQueryModel()
      })
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
      this.$refs['model'].emitDoSql()
    },
    getDataList () {
      this.$emit('refreshDataList')
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      // this.$emit('refreshDataList')
      this.visible = false
    },
    dataFormSubmitHandle () {
      this.verifyForm()
        .then(() => {
          const params = {
            ...this.dataForm
          }
          var _self = this
          if (!params.gadgetType) {
            return this.$message.error('Please Select Gadget')
          }
          if (params.gadgetType !== _self.oldGadgetType) {
            params.gadgetSetting = {}
          }
          if (!params.businessId) {
            params.businessId = getUUID()
          }
          this.$interface.reports.postReportSetting(params)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return _self.$message.error(res.msg)
              }
              if (res.data.exist) {
                _self.$message.error(_self.$t('custom.dataset.nameexist'))
              } else {
                _self.visible = false
                _self.$emit('refreshDataList')
                return _self.$message.success(res.msg)
              }
            })
        })
    },
    verifyForm () {
      return this.$refs['dataForm'].validate()
    },
    getUserList () {
      const param = {
        status: 1
      }
      this.$interface.schedule.getWorkScheduledUserListApi(param)
        .then(({ data: res }) => {
          this.loading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.userList = res.data
        }).catch(() => {
          this.loading = false
        })
    },
    getIntegrationList () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode,
        loadType: 3
      }
      return this.$interface.taskManager.getConnectorInfoNew(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          let mapObj = res.data
          let tempList = []
          for (let key in mapObj) {
            tempList.push({
              name: mapObj[key].name,
              subjectCode: mapObj[key].sync.subjectCode,
              status: mapObj[key].sync.status
            })
          }
          this.integrationList = tempList
        })
        .catch(() => { })
    },
    clearFormData () {
      this.dataForm = {
        id: null,
        name: null,
        integration: [],
        businessId: null,
        businessType: null,
        type: 1,
        description: null,
        tenantCode: this.$store.state.user.tenantCode,
        status: null,
        reuse: true,
        gadgetId: null,
        gadgetType: null,
        gadgetSetting: {},
        datasetSetting: {},
        formSetting: {},
        filterSettings: {},
        sqlExpress: {},
        owner: null,
        // about DA
        internalNotes: null,
        uat: null,
        overheadFilters: null,
        allClientsQa: null,
        reportingQa: null,
        priority: null,
        eta: null,
        client: null,
        progress: null
      }
    }
  }
}
</script>

<style lang="scss" >
.cursor_pointer {
  cursor: pointer;
}
.widget_card {
  box-shadow: 0 0 8px 0 #f0f0f0;
  border: 1px solid #fcfcfc;
}
.widget_card:hover {
  box-shadow: 0 2px 12px -4px #c2c7d0;
  border: 1px solid #fcfcfc;
}
.right-text {
  white-space: normal;
  word-break: normal;
}
.div-background {
  background-image: url("#{$--ossLink}/app/gadget/select-widget-background.png") !important;
  background-repeat: no-repeat !important;
  background-position: right bottom !important;
  background-size: contain !important;
}
.search-div {
  width: 200px;
  margin-bottom: 10px;
  margin-top: -10px;
}
.div-background ::v-deep .el-tabs__header {
  width: 30% !important;
  margin: 0 0 15px !important;
}
.widget_data_list {
  margin-top: 20px;
  min-height: 20px;
  .el-checkbox-group {
    > .is-checked {
      border: 1px solid #138dc7;
      .el-checkbox__inner {
        // background-image: url('../../../../assets/add_reports_radio_selected.png');
        // background-repeat: no-repeat;
        // background-position: center;
        // background-size: 14px 14px;
      }
      .el-checkbox__inner::after {
        // transform: rotate(0deg) scaleY(0);
      }
    }
    .el-checkbox__inner {
      // border: 0;
      // background-image: url('../../../../assets/add_reports_radio.png');
      // background-repeat: no-repeat;
      // background-position: center;
      // background-size: 14px 14px;
      // background-color: transparent;
    }
  }
  .el-checkted {
    // border: 1px solid #138DC7 !important;
  }
  .el-checkbox {
    display: block;
    margin-right: 0;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    margin-top: 10px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .el-checkbox__input {
      display: block;
      width: 54px;
      text-align: center;
    }
    .el-checkbox__label {
      flex: 1;
      display: block;
      height: 100%;
      padding-left: 0;
      .item_widget3 {
        // background: url('../../../../assets/grid.png');
        background-size: 48px 48px;
        background-repeat: no-repeat;
        background-position: left center;
        height: 100%;
        padding-left: 54px;
        padding-top: 5px;
        padding-bottom: 5px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        min-height: 70px;
        .item_widget_content {
          flex: 1;
          height: 100%;
          padding-right: 10px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          > div {
            white-space: pre-wrap;
            word-break: break-word;
          }

          > div:nth-child(1) {
            color: #000;
            font-size: 14px;
          }
          > div:nth-child(2) {
            font-size: 14px;
            color: rgba(0, 0, 0, 0.49);
          }
        }
        .item_widget_ri {
          float: right;
          width: 53px;
          height: 100%;
          text-align: center;
          .item {
            height: 14px;
            width: 14px;
            border: 0;
            background: url("../../../assets/select_widget_eye.png");
            background-size: 14px 14px;
            background-repeat: no-repeat;
            background-position: center;
          }

          // box-shadow: -1px 0px 0px 0px #F0F0F0;
          // margin: 5px 0;
        }
        position: relative;
      }
      .item_widget3::after {
        content: "";
        clear: both;
        display: block;
        overflow: hidden;
        // height: 0;
        position: absolute;
        right: 53px;
        border-right: 1px solid #f0f0f0;
        height: 80%;
      }
    }
  }
  .el-checkbox::after {
    content: ".";
    clear: both;
    display: block;
    overflow: hidden;
    height: 0;
  }
}
</style>
